<template>
  <section>
      <div>
          <div class="button-list">
              <div class="flex">
                  <el-dropdown @command="handleCommand" v-if="wmks">
                      <el-button plain>
                          发送远程命令<el-icon class="m-left8"><ArrowDown /></el-icon>
                      </el-button>
                      <template #dropdown>
                          <el-dropdown-menu>
                              <el-dropdown-item
                                  v-for="(item, index) in command"
                                  :key="index"
                                  :command="item.comm"
                                  :disabled="checkDisabled(item)">
                                  {{ item.name }}
                              </el-dropdown-item>
                          </el-dropdown-menu>
                      </template>
                  </el-dropdown>
                  <span class="m-left8">
                    {{ connectedText }}
                  </span>
              </div>
              <div>
                  <span class="m-right-8">提示：如果出现持续黑屏，说明系统处于休眠状态，按任意键可以激活</span>
                  <el-button  plain @click="dialogVisible = true">复制命令输入</el-button>
                  <el-button v-if="!info"  plain @click="fullScreen">全屏</el-button>
              </div>
          </div>
          <div style="width: 100%;">
            <el-row>
              <el-col :span="18">
                <div
                  v-show="connectedStatus == 'connected'"
                  id="wmksContainer">
                </div>
              </el-col>
              <el-col :span="5">
                <div class="m-t-20 right-tip">注：关闭页面时，请输入exit退出用户登录</div>
              </el-col>
            </el-row>
          </div>
          
          <div v-if="pcFlag && connectedStatus != 'connected' && connectedStatus != 'connecting'" class="shut-down">
              <!-- 连接已断开 -->
          </div>
          <div v-if="!pcFlag" class="shut-down">
              浏览器不支持，请在PC端打开！
          </div>
          <el-dialog
              title="复制粘贴命令"
              v-model="dialogVisible"
              width="800px"
              :before-close="handleClose">
              <div class="copy-command-content">
                  <el-alert
                      :title="alertTitle"
                      :type="alertFlag ? 'success' : 'error'">
                  </el-alert>
                  <el-form class="command-text-content" ref="form" label-width="80px">
                      <el-form-item label="文本内容：">
                          <el-input
                              type="textarea"
                              :rows="8"
                              placeholder="请输入复制粘贴命令"
                              v-model="commandText"
                              maxlength="2000"
                              show-word-limit>
                          </el-input>
                      </el-form-item>
                  </el-form>
              </div>
              <template #footer>
                  <el-button @click="handleClose">取 消</el-button>
                  <el-button type="primary" @click="submitCommandText">确 定</el-button>
              </template>
          </el-dialog>
      </div>
      <!--按需引入外部js-->
      <remote-script @loadData="js1 = true" src="console/jquery-1.8.3.min.js"></remote-script>
      <remote-script v-if="js1" @loadData="js2= true" src="console/jquery-ui.min.js"></remote-script>
      <remote-script v-if="js2"  @loadData="js3= true" src="console/wmks.min.js"></remote-script>
      <remote-css href="console/wmks-all.css"></remote-css>
  </section>

</template>
<script>
import httpServer from '@/service/console'
import { CONF, isPC } from '@/utils/console'
import Utils from '@/utils/newUtils'
import RemoteScript from '@/utils/importJs.js'
import RemoteCss from '@/utils/importCss.js'

export default {
  components: {RemoteScript, RemoteCss},
  data(){
  return {
    wmks: null,
    text: '',
    connectedText: '等待连接',
    connectedStatus: 'connected',
    dialogVisible: false,
    alertTitle: '将内容粘贴至文本框中，最大支持2000个字符，暂不支持中文等非标准键盘值特殊字符',
    alertType: 'success',
    commandText: '',
    alertFlag: true,
    command: [
      {
        name: '连接远程连接',
        comm: 'connect',
      },
      {
        name: '断开远程连接',
        comm: 'shutdown'
      },
      {
        name: 'CTRL+ALT+DELETE',
        comm: 'CAD'
      },
      {
        name: 'CTRL+ALT+F1',
        comm: '17,18,112'
      },
      {
        name: 'CTRL+ALT+F2',
        comm: '17,18,113'
      },
      {
        name: 'CTRL+ALT+F3',
        comm: '17,18,114'
      },
      {
        name: 'CTRL+ALT+F4',
        comm: '17,18,115'
      },
      {
        name: 'CTRL+ALT+F5',
        comm: '17,18,116'
      },
      {
        name: 'CTRL+ALT+F6',
        comm: '17,18,117'
      },
      {
        name: 'CTRL+ALT+F7',
        comm: '17,18,118'
      },
      {
        name: 'CTRL+ALT+F8',
        comm: '17,18,119'
      },
      {
        name: 'CTRL+ALT+F9',
        comm: '17,18,120'
      },
      {
        name: 'CTRL+ALT+F10',
        comm: '17,18,121'
      },
    ],
    pcFlag: true,
    info: null,
      js1: false,
      js2: false,
      js3: false,
      
  }
},
computed: {
  id(){
    return this.$route.params.id
  },
  os_type(){
    return this.$route.params.os_type
  },
  instance(){
    return this.$route.params.name
  },
    jsFlag(){
      return this.js1 && this.js2 && this.js3
    }
},
  watch: {
      jsFlag(val){
          if(val){
              this.init()
          }
      }
  },
methods: {
  enterTab(){},
  leaveTab(){},
  ControlV(){},
  handleClose(){
    this.dialogVisible = false
    this.commandText = ''
  },
  fullScreen(){
    const wmksContainer = document.getElementById('wmksContainer')
    if(wmksContainer.requestFullscreen) {
        wmksContainer.requestFullscreen()
    } else if(wmksContainer.mozRequestFullScreen) {
        wmksContainer.mozRequestFullScreen()
    } else if(wmksContainer.webkitRequestFullscreen) {
        wmksContainer.webkitRequestFullscreen()
    } else if(wmksContainer.msRequestFullscreen) {
        wmksContainer.msRequestFullscreen()
    }
    this.wmks = null
    this.connectedStatus = null
    this.$nextTick(() => {
      this.getWebUrl()
    })
  },
  submitCommandText(){
    if(!CONF.command.test(this.commandText)){
      this.$message.error('暂不支持中文等非标准键盘值特殊字符！')
      return
    }
    this.wmks.sendInputString(this.commandText)
    this.handleClose()
  },
  checkDisabled(item){
    if(item.comm == 'connect'){
      if(this.connectedStatus == WMKS.CONST.ConnectionState.CONNECTED){
        return true
      }
      return false
    }
    return false
  },
  handleCommand(comm){
    if(comm == 'shutdown'){
      if(this.wmks){
        this.wmks.disconnect()
        this.connectedText = this.info ? '连接已断开，请关闭页面' : '成功断开'
        this.wmks = null
        this.connectedStatus = null
      }
    }else if(comm == 'connect'){
      this.getWebUrl()
    }else if(comm == 'CAD'){
      this.wmks.sendCAD()
    }else{
      this.wmks.sendKeyCodes(comm.split(',').map(item => Number(item)))
    }
  },
  sendKeyCode(type){
    if(JSON.stringify(this.wmks) != '{}'){
      if(type == 'CAD'){
        this.wmks.sendCAD()
      }else{
        this.wmks.sendKeyCodes(type.split(',').map(item => Number(item)))
      }
    }
  },
  formatUrl(obj){
      let proxyUrl = process.env.VUE_APP_WEB_CONSOLE_URL;
      if(window.location.origin.indexOf('.test')>-1){
          proxyUrl = 'ws://10.13.132.1:80'
      }
   
      return `${proxyUrl}/html_console/args?info=${obj.info}`
  },
  updateWMKS(wmks){
    const wmksContainer = document.querySelector('#wmksContainer')
    const width = wmksContainer.clientWidth
    const height = wmksContainer.clientHeight
    this.wmks.setOption('changeResolution', true)
    this.wmks.setRemoteScreenSize(width, height)
    this.wmks.updateScreen()
  },
  web_wmks (obj) {
    console.log('执行web_wmks', obj)
    const self = this
    const wmksContainer = document.querySelector('#wmksContainer')
    const width = wmksContainer.clientWidth
    const height = wmksContainer.clientHeight
    const url = this.formatUrl(obj)
    const option = {
        rescale: true,
        reverseScrollY: true,
    }
    this.wmks = WMKS
        .createWMKS("wmksContainer", option)
        .register(WMKS.CONST.Events.CONNECTION_STATE_CHANGE, this.connectionStateHandler)
    this.updateWMKS()
    this.wmks.connect(url)
  },
  connectionStateHandler(event, data){
    this.connectedStatus = data.state
    if (data.state == WMKS.CONST.ConnectionState.CONNECTED) {
      this.connectedText = `成功连接到实例：${this.instance}`
    }else{
      this.connectedText = this.info ? '连接已断开，请关闭页面' : '成功断开'
    }
  },
  lintenPaste(){
      const self = this
      document.addEventListener('paste', function(event){
        var clipboardData = (event.clipboardData || event.originalEvent.clipboardData)
        if(!clipboardData || !clipboardData.items){
            self.$message.error('浏览器不支持')
            return
        }
        const text = clipboardData.getData('text')
        self.wmks.sendInputString(text)
      })
  },
  async getWebUrl(){
    const reqData = {'vm_id': this.id}
    const { data, code, msg } = await httpServer.get_vm_ticket(reqData)
    if(data && code === 'Success'){
      this.web_wmks(data)
      // this.lintenPaste()
    }else{
      this.$message.error(msg || '获取失败')
    }
  },
  init(){
      // 从url上取info的值，如果存在info，直接使用info请求socket
      const info = Utils.getQueryString('info')
      this.info = info
      if(info && this.pcFlag){
          this.command = [
              {
                  name: '断开远程连接',
                  comm: 'shutdown'
              },
              {
                  name: 'CTRL+ALT+DELETE',
                  comm: 'CAD'
              },
              {
                  name: 'CTRL+ALT+F1',
                  comm: '17,18,112'
              },
              {
                  name: 'CTRL+ALT+F2',
                  comm: '17,18,113'
              },
              {
                  name: 'CTRL+ALT+F3',
                  comm: '17,18,114'
              },
              {
                  name: 'CTRL+ALT+F4',
                  comm: '17,18,115'
              },
              {
                  name: 'CTRL+ALT+F5',
                  comm: '17,18,116'
              },
              {
                  name: 'CTRL+ALT+F6',
                  comm: '17,18,117'
              },
              {
                  name: 'CTRL+ALT+F7',
                  comm: '17,18,118'
              },
              {
                  name: 'CTRL+ALT+F8',
                  comm: '17,18,119'
              },
              {
                  name: 'CTRL+ALT+F9',
                  comm: '17,18,120'
              },
              {
                  name: 'CTRL+ALT+F10',
                  comm: '17,18,121'
              },
          ]
          this.web_wmks({ info })
      }else{
          // url上info不存在时，调用接口获取info
          if(this.pcFlag){
              this.getWebUrl()
          }
      }
  }
},
mounted(){
   // this.init()
},
created () {
  this.pcFlag = isPC()
}
}
</script>
<style scoped lang="scss">
#wmksContainer{
position:absolute;
width:54vw;
height:72vh;
left: 19vw;
margin-top: 20px;
/* touch-action: none */
}
#mainCanvas{
height: 90vh !important;
}
.window-tools{
position: absolute;
left: 50%;
transform: translateX(-50%);
z-index: 3;
width: 500px;
text-align: center;
height: 35px;
line-height: 35px;
background-color: rgba(255,255,255,1);
border-radius: 5px;
}
.button-list{
display: flex;
justify-content: space-between;
padding: 10px 20px;
background-color: #F2F2FB;
}
.copy-command-content{
padding: 30px 50px;
}
.command-text-content{
padding-top: 30px;
}
.shut-down{
padding: 50px;
text-align: center;
font-size: 25px;
color: red;
}
.right-tip {
  font-size: 40px;
  color: red;
}
</style>
